# coding:utf-8
import json
import traceback

from django.db import transaction
from django.db.models import Q

from app.autojob.models import TicketRecord, OSSystemInstallHaveSN, InitTaskList, TaskRecord, InitTaskConfig
from app.autojob.shell_exec import run_command, ssh_login
from app.cron.data_opt import execute_remote_workflow
from common.libs.common_data_opt import del_dict_key, time_trans_str_s
from app.cron.tasks import create_init_task


def ticket_detail_tree_data(param):
    """获取工单与sn树"""
    username = param.get('username', None)
    info = TicketRecord.objects.using('loonflow').filter(act_state_id=1, workflow_id=11, participant__icontains=username).values('id', 'sn')
    if not info:
        return []

    data = []
    for item in info:
        sn_info = OSSystemInstallHaveSN.objects.using('server-platform').filter(ticket_id=item['id']).values()
        children = []
        if sn_info:
            for sn in sn_info:
                children.append({
                    "label": sn["sn"],
                    "id": str(sn["id"]) + '-' + sn["sn"],
                    "order_no": item["sn"],
                    "businessIp": sn["internal_ip_config"],
                    "systemSN": sn["sn"],
                    "ticketSn": item["sn"],
                    "ticketId": item["id"],
                    "idc": sn["source_computer_room"],
                    "rackBuilding": sn["source_building"],
                    "netmask": sn["netmask"],
                    "gateway": sn["gateway"],
                    "create_user": username
                })
            data.append({"label": item["sn"], "id": str(item["id"]) + '-' + item["sn"], "ticket_id": item["id"], "children": children})
    return data


def submit_task_data(request, data):
    """提交任务列表"""
    table_data = data.get('taskData', None)
    if not table_data:
        return False, '提交任务失败，未获取到任务数据'
    try:
        table_data = json.loads(table_data)
        username = request.session['username']
        nickname = request.session['nickname']
        with transaction.atomic():
            for item in table_data:
                tmp = del_dict_key(item, ['label', 'id', 'order_no', '_XID'])
                if InitTaskList.objects.filter(systemSN=tmp.get('systemSN')).filter(~Q(status__icontains="完成")).exists():
                    return False, f"{tmp.get('systemSN')} 已存在与进行中的初始化任务列表中"
                tmp['status'] = '初始化中'
                if not tmp['netmask']:
                    tmp['netmask'] = None
                res = InitTaskList.objects.create(**tmp)
                u_id = res.id
                res.save()
                TaskRecord.objects.create(taskType='初始化任务', taskId=u_id, nodeName='初始化中', operationUserAccount=username,
                                          operationCnName=nickname, status='正常').save()
                create_init_task.delay(tmp['businessIp'], u_id, username, nickname)
    except Exception as e:
        traceback.print_exc()
        return False, str(e)
    return True, 'success'


def get_task_log(param):
    """获取 任务详情流转日志"""
    u_id = param.get('taskId', None)
    if not u_id:
        return False, '获取任务详情日志失败', []
    info = list(TaskRecord.objects.filter(taskId=u_id).values())
    for item in info:
        item['createTime'] = time_trans_str_s(item['createTime'])
    return True, 'success', info


def clear_init_log(u_id):
    """清空初始化日志log"""
    info = InitTaskConfig.objects.all().first()
    if not info:
        return False, '获取账户失败'
    username = info.username
    password = info.password
    init_log_path = info.initLogPath
    bond_log_path = info.bondLogPath

    host = InitTaskList.objects.filter(id=u_id).values().first()

    res, ssh = ssh_login(host['businessIp'], username, password)
    if not res:
        return False, '远程SSH登录失败', ''

    init_stdout, _ = run_command(ssh, f"cat /dev/null > {init_log_path}")
    net_stdout, _ = run_command(ssh, f"cat /dev/null > {bond_log_path}")

    ssh.close()
    return True, 'success'


def retry_task(request, data):
    """任务重试"""
    u_id = data.get('taskId', None)
    if not u_id:
        return False, '获取任务id'

    username = request.session['username']
    nickname = request.session['nickname']

    res, msg = clear_init_log(u_id)
    if not res:
        return False, msg

    try:
        InitTaskList.objects.filter(id=u_id).update(status='初始化中')
        info = InitTaskList.objects.filter(id=u_id).first()
        TaskRecord.objects.create(taskType='初始化任务', taskId=u_id, nodeName='初始化中', operationUserAccount=username,
                                  operationCnName=nickname, status='正常').save()
        create_init_task.delay(info.businessIp, u_id, username, nickname)
    except Exception as e:
        traceback.print_exc()
        return False, str(e)
    return True, 'success'


def get_init_script_log(param):
    """获取初始化脚本log"""
    u_id = param.get('taskId', None)
    flag = param.get('flag', None)
    if not u_id:
        return False, '获取脚本运行日志失败', ''

    info = InitTaskConfig.objects.all().first()
    if not info:
        return False, '获取账户失败', ''
    username = info.username
    password = info.password
    init_log_path = info.initLogPath
    bond_log_path = info.bondLogPath
    host = InitTaskList.objects.filter(id=u_id).values().first()
    res, ssh = ssh_login(host['businessIp'], username, password)
    if not res:
        return False, '远程SSH登录失败', ''

    init_stdout, _ = run_command(ssh, f"cat {init_log_path}")
    net_stdout, _ = run_command(ssh, f"cat {bond_log_path}")

    ssh.close()
    all_log = []

    # 合并标准输出
    for stdout in (init_stdout, net_stdout):
        if stdout:
            all_log.extend(stdout.splitlines())

    # 根据标志位筛选日志
    if flag == 'fail':
        log = [item for item in all_log if 'Fail' in item]
    else:
        log = all_log

    return True, 'success', log


